<template>
<div>
    <section id="app" class="todoapp">
    <header class="header">
      <h1>todos</h1>
      <input
        class="new-todo"
        placeholder="What needs to be done?"
        autocomplete="off"
        autofocus
        v-model="input"
        @keydown.enter="addTodo"
        >
    </header>
    <section class="main" v-show="count">
      <input id="toggle-all" class="toggle-all" type="checkbox" v-model="allDone">
      <label for="toggle-all">Mark all as complete</label>
      <ul class="todo-list">
        <li v-for="todo in filterTodos" :key="todo" :class="
        {editing:todo === edittingTodo,completed:todo.completed}"  @dblclick="editTodo(todo)">
          <div class="view">
            <input class="toggle" type="checkbox" v-model="todo.completed">
            <label>{{todo.text}}</label>
            <button class="destroy" @click="remove(todo)"></button>
          </div>
          <input class="edit" type="text" v-model="todo.text"
          @keyup.enter="doneEdit(todo)"
          @blur="doneEdit(todo)"
          @keyup.esc="cancleEdit(todo)"
          v-focus="todo === edittingTodo"
          >
        </li>
      </ul>
    </section>
    <footer class="footer"  v-show="count ">
      <span class="todo-count">
        <strong>{{remainingCount}}</strong> {{remainingCount>1?'items':'item'}} left
      </span>
      <ul class="filters">
        <li><a href="#/all">All</a></li>
        <li><a href="#/active">Active</a></li>
        <li><a href="#/completed">Completed</a></li>
      </ul>
      <button class="clear-completed" @click="removeCompleted" :remainingCount="remainingCount" :count="count" v-show="count > remainingCount">
        Clear completed
      </button>
    </footer>
  </section>
  <footer class="info">
    <p>Double-click to edit a todo</p>
    <!-- Remove the below line ↓ -->
    <p>Template by <a href="http://sindresorhus.com">Sindre Sorhus</a></p>
    <!-- Change this out with your name and url ↓ -->
    <p>Created by <a href="https://shiguanghai.top">shiguanghai</a></p>
    <p>Part of <a href="http://todomvc.com">TodoMVC</a></p>
  </footer>
</div>
</template>

<script>
import './assets/index.css'
import { computed, onMounted, onUnmounted, ref, watchEffect } from 'vue'
import useLocalStorage from '@/utils/useLocalstorage.js'
const storage = useLocalStorage()
// 1.add todo
const useAddTodo = todos => {
  const input = ref('')
  const addTodo = () => {
    const text = input.value && input.value.trim()
    if (text.length === 0) return
    todos.value.unshift({ text, completed: false })
    input.value = ''
  }
  return {
    input,
    addTodo
  }
}

// 2.delete todo
const useRemove = todos => {
  const remove = todo => {
    const index = todos.value.indexOf(todo)
    todos.value.splice(index, 1)
  }
  const removeCompleted = () => {
    todos.value = todos.value.filter(todo => !todo.completed)
  }
  return {
    remove,
    removeCompleted
  }
}

// 3.edit todo
const useEdit = remove => {
  let beforeEdittingText = ''
  let edittingTodo = ref(null)
  // 标记正在编辑的对象
  const editTodo = todo => {
    beforeEdittingText = todo.text
    edittingTodo.value = todo
  }
  // 编辑完成
  const doneEdit = todo => {
    if (!edittingTodo.value) return
    todo.text = todo.text.trim()
    todo.text || remove(todo)
    edittingTodo.value = null
  }
  // 取消编辑
  const cancleEdit = todo => {
    edittingTodo = null
    todo.text = beforeEdittingText
  }
  return {
    edittingTodo,
    editTodo,
    cancleEdit,
    doneEdit
  }
}

// 4.filter
const useFilter = todos => {
  const allDone = computed({
    get () {
      return todos.value.every(todo => todo.completed)
    },
    set (value) {
      console.log(1)
      todos.value.forEach(todo => {
        todo.completed = value
      })
    }
  })
  const filter = {
    all: list => list,
    active: list => list.filter(todo => !todo.completed),
    completed: list => list.filter(todo => todo.completed)
  }
  const type = ref('all')
  const filterTodos = computed(() => {
    return filter[type.value](todos.value)
  })
  const onHashChange = () => {
    const hash = window.location.hash.replace('#/', '')
    if (filter[hash]) {
      type.value = hash
    } else {
      type.value = 'all'
      window.location.hash = ''
    }
  }
  const remainingCount = computed(() => filter.active(todos.value).length)
  const count = computed(() => todos.value.length)
  onMounted(() => {
    window.addEventListener('hashchange', onHashChange)
    onHashChange()
  })
  onUnmounted(() => {
    window.removeEventListener('hashchange')
  })
  return {
    count,
    allDone,
    filterTodos,
    remainingCount
  }
}

// 5. storage
const useStorage = () => {
  const KEY = 'TODO_LIST'
  const todos = ref(storage.getItem(KEY) || [])
  watchEffect(() => {
    storage.setItem(KEY, todos.value)
  })
  return todos
}

export default {
  name: 'App',
  setup () {
    const todos = useStorage()
    const { remove, removeCompleted } = useRemove(todos)
    return {
      todos,
      ...useAddTodo(todos),
      remove,
      removeCompleted,
      ...useEdit(remove),
      ...useFilter(todos)
    }
  },
  directives: {
    focus (el, binding) {
      binding.value && el.focus()
    }
  }
}
</script>

<style>
</style>
